#!/bin/sh
# Copyright 2021 Stan Grishin (stangri@melmac.net)
# shellcheck disable=SC1091,SC2039

# TechRef: https://openwrt.org/docs/techref/rpcd

. /lib/functions.sh
. /usr/share/libubox/jshn.sh

pkgName="vpnbypass"

is_enabled() { uci -q get "${1}.config.enabled"; }
is_running() { iptables -t mangle -L | grep -q VPNBYPASS && echo '1' || echo '0'; }
get_version() { grep -A2 -w "Package: $1$" /usr/lib/opkg/status | sed -n 's/Version: //p'; }
print_json_bool() { json_init; json_add_boolean "$1" "$2"; json_dump; json_cleanup; }
print_json_string() { json_init; json_add_string "$1" "$2"; json_dump; json_cleanup; }
logger() { /usr/bin/logger -t "$pkgName" "$@"; }

get_init_list() {
	local name="$1"
	json_init
	json_add_object "$name"
	json_add_boolean 'enabled' "$(is_enabled "$name")"
	json_add_boolean 'running' "$(is_running "$name")"
	json_close_object
	json_dump
	json_cleanup
}

set_init_action() {
	local name="$1" action="$2" cmd
	if [ ! -f "/etc/init.d/$name" ]; then
		print_json_string 'error' 'Init script not found!'
		return
	fi
	case $action in
		enable)
			cmd="uci -q set ${name}.config.enabled=1 && uci commit $name";;
		disable)
			cmd="uci -q set ${name}.config.enabled=0 && uci commit $name";;
		start|stop|reload|restart)
			cmd="/etc/init.d/${name} ${action}";;
	esac
	if [ -n "$cmd" ] && eval "${cmd}" 1>/dev/null 2>&1; then
		print_json_bool "result" '1'
	else
		print_json_bool "result" '0'
	fi
}

get_init_status() {
	local name="$1"
	json_init
	json_add_object "$name"
	json_add_boolean 'enabled' "$(is_enabled "$name")"
	json_add_boolean 'running' "$(is_running "$name")"
	json_add_string 'version' "$(get_version "$name")"
	json_close_object
	json_dump
	json_cleanup
}

case "$1" in
	list)
		json_init
		json_add_object "getInitList"
			json_add_string 'name' 'name'
		json_close_object
		json_add_object "setInitAction"
			json_add_string 'name' 'name'
			json_add_string 'action' 'action'
		json_close_object
		json_add_object "getInitStatus"
			json_add_string 'name' 'name'
		json_close_object
		json_dump
		json_cleanup
		;;
	call)
		case "$2" in
			getInitList)
				read -r input
				json_load "$input"
				json_get_var name 'name'
				json_cleanup
				get_init_list "$name"
				;;
			getInitStatus)
				read -r input
				json_load "$input"
				json_get_var name 'name'
				json_cleanup
				get_init_status "$name"
				;;
			setInitAction)
				read -r input
				json_load "$input"
				json_get_var name 'name'
				json_get_var action 'action'
				json_cleanup
				set_init_action "$name" "$action"
				;;
		esac
	;;
esac
